/**
 * \file
 *
 * \brief 薄膜键盘扫描程序
 *
 * \author 高明飞
 *
 * \date 2015-09-25
 *
 * 修改记录：\n
 *
 */
 
#include "KeyBoard.h"

/** 记录按下的键 */
uint8_t KeyBoard_State = 0x00;
/** 上一次按下的键 */
static uint8_t KeyBoard_Last_State = 0x00;


/**
 * 模仿触发器原理实现边缘检测
 */
static void KeyBoard_FF(void);

/**
 * 扫描键盘
 */
void KeyBoard_Scan(void)
{
	uint8_t tmpdata,i;
	
	KEY1 = 1;
	KEY2 = 1;
	KEY3 = 1;
	KEY4 = 1;
	/* Delay */
	for(i = 0; i < 10; i++);
	
	KEY1 = 0;
	/* Delay */
	for(i = 0; i < 10; i++);
	tmpdata = COMData;
	for(i = 0; i < 8; i++)
	{
		if((tmpdata & 0x01) == 0)
		{
			KeyBoard_State = 0x10 + i;
			KEY1 = 1;
			KeyBoard_FF();
			return;
		}
		
		tmpdata >>= 1;
	}
	KEY1 = 1;
	
	KEY2 = 0;
	/* Delay */
	for(i = 0; i < 10; i++);
	tmpdata = COMData;
	for(i = 0; i < 8; i++)
	{
		if((tmpdata & 0x01) == 0)
		{
			KeyBoard_State = 0x20 + i;
			KEY2 = 1;
			KeyBoard_FF();
			return;
		}
		
		tmpdata >>= 1;
	}
	KEY2 = 1;
	
	KEY3 = 0;
	/* Delay */
	for(i = 0; i < 10; i++);
	tmpdata = COMData;
	for(i = 0; i < 8; i++)
	{
		if((tmpdata & 0x01) == 0)
		{
			KeyBoard_State = 0x30 + i;
			KEY3 = 1;
			KeyBoard_FF();
			return;
		}
		
		tmpdata >>= 1;
	}
	KEY3 = 1;
	
	KEY4 = 0;
	/* Delay */
	for(i = 0; i < 10; i++);
	tmpdata = COMData;
	for(i = 0; i < 8; i++)
	{
		if((tmpdata & 0x01) == 0)
		{
			KeyBoard_State = 0x40 + i;
			KEY4 = 1;
			KeyBoard_FF();
			return;
		}
		
		tmpdata >>= 1;
	}
	KEY4 = 1;
	
	KeyBoard_FF();
	
}

/**
 * 模仿触发器原理实现边缘检测
 */
static void KeyBoard_FF()
{
	if(KeyBoard_State == KeyBoard_Last_State)
	{
		KeyBoard_Last_State = KeyBoard_State;
		KeyBoard_State = 0x00;
	}
	else
		KeyBoard_Last_State = KeyBoard_State;
}


